package com.xhl.demo.controller;

import cn.hutool.core.io.IoUtil;
import com.xhl.demo.domain.FileInfo;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author 徐宏亮
 * @description
 * @date 2019/1/15 21:34
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private String folder = "D:/File/ideaProject/SpringBoot-Shop-First/shop-demo/src/main/java/com/xhl/demo/controller";
//    private String folder = "E:\\IdeaProjects\\SpringBoot-Shop-First\\shop-security-demo\\src\\main\\java\\com\\xhl\\shop\\shopsecuritydemo\\controller";

    @PostMapping
    public FileInfo upload(MultipartFile file) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        File localFile = new File(folder, System.currentTimeMillis() + ".txt");
        //将上传的文件数据写入新建的文件
        file.transferTo(localFile);

        //实际应用写到服务器上，获取输入流
        //InputStream inputStream = file.getInputStream();
        //写到任何地方
        //...



        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //jdk 7 语法，括号内声明的流，会自动关闭
        try (
                InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
                OutputStream outputStream = response.getOutputStream()) {

            response.setContentType("application/x-download");
            //这里没有生效，待解决
            response.addHeader("Content-Disposition", "attachment;filename-test.txt");

            // 文件输入流写到输出流
            IoUtil.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
